/***
 * 对 axios 网络请求框架的使用进行包装.
 */

import  axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import URL_MAIN from  '../../pages/js/baseUrl'
import router from '../../router/index'
import Constant from '../../config/TiyConfig'
import store from '../../store/index'
import MTypes from "../../store/types/TypesMutation"

// axios.defaults.baseURL = Constant.baseUrl;



var axiosInstance = axios.create({
  baseURL:  Constant.baseUrl,
  timeout: 30000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  withCredentials: true,//可带cookie 必须
});

//拦截器
axiosInstance.interceptors.request.use((request) => {

  let REQUEST_DATA = request.data;
  request.data = qs.stringify(REQUEST_DATA);
  return request;

}, function (error) {
  return Promise.reject(error);
});

axiosInstance.interceptors.response.use(
  function (response) {
    return checkStatus(response);
  },
  function (error) {
    return Promise.reject(error);
  }
  );


function checkStatus(response) {
  if(response!==undefined&&response.data!==undefined ){
    if (response.data.errorCode ===501){
      Vue.prototype.$Message.info({
        content: '用户令牌过期,请重新登录',
        duration: 5
      });
      store.commit(MTypes.user.clearUserInfo);
      router.push(URL_MAIN.ALogin);
      //机器尚未授权
    }else if (response.data.errorCode === 701 || response.data.errorCode === 702 || response.data.errorCode === 703){
        // Vue.prototype.$Modal.warning({content :response.data.errorMessage});
        store.commit(MTypes.user.clearUserInfo);
        store.commit(MTypes.local.storeIsNeedFinger, true);
        router.push( { path: URL_MAIN.ALogin, replace:true});
    }

  }else if (response.status === -404){
    Vue.prototype.$Message.info({
      content: '服务器没有响应，请稍后再试404',
      duration: 5
    });
  }
  return response ;
}

/**
 * 构造超时响应
 * @param error
 */
function timeoutResponse(error){
  Vue.prototype.$Message.info({
    content: '服务器没有响应，请稍后再试',
    duration: 5
  });
  var data = {};
  data.success = false;
  data.errorCode = 250;
  data.errorMessage = error;
  return data;
}

export default {
  post (url, data) {
    return axiosInstance.post(url,data).then((res) => {
      return res.data;
    }).catch(function (error) {
      return timeoutResponse(error);
    });
  },
  /**
   * @param url
   * @param data
   * @param time 请求超时时间，单位秒
   * @returns {Promise<AxiosResponse<AxiosResponse<AxiosResponse<AxiosResponse<T>>>>>}
   */
  post (url, data,time) {
    return axiosInstance.post(url, data, {timeout: 1000*time}).then((res) => {
      return res.data;
    }).catch(function (error) {
      return timeoutResponse(error);
    });
  }
};


